package com.example.smartagriculture.controller;

import com.example.smartagriculture.utils.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/fileController")
public class FileController {

    @ResponseBody
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            System.out.println("上传失败，因为文件为空.");
            return Result.error("上传失败，因为文件为空.");
        }

        String saveFileName = Paths.get(file.getOriginalFilename()).getFileName().toString(); // 避免路径遍历攻击

        String directoryPath = new File("upload/image/").getAbsolutePath(); // 相对路径
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        Path savePath = Paths.get(directoryPath, saveFileName);
        Files.write(savePath, file.getBytes());
        return Result.success(saveFileName);
    }
}
